package com.xbjtech.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.xbjtech.model.User;
import com.xbjtech.service.UserService;

public class CustomRealm extends AuthorizingRealm {
	
	@Autowired
	UserService userService;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO 应该从数据库里查询当前登陆用户的角色和权限
		@SuppressWarnings("unused")
		User user = (User) principals.getPrimaryPrincipal();
		// TODO 授权 （给角色给权限）
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addRole("admin");
		info.addRole("user");
		info.addRole("manager");
		info.addStringPermission("user:addbtn");
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken principal = (UsernamePasswordToken) token;
		// TODO 认证 （登陆）
		User user = userService.getUserByUsername(principal.getUsername());
		if (null == user) {
			throw new UnknownAccountException("用户名不存在");
		}
		ByteSource salt = ByteSource.Util.bytes(user.getId().toString());
		return new SimpleAuthenticationInfo(user, user.getPassword(), salt, getName());
	}
	
	public static void main(String[] args) {
		SimpleHash simpleHash = new SimpleHash("SHA-256", "123456", ByteSource.Util.bytes("1"), 100);
		System.out.println(simpleHash);
	}

	

}
